package com.sdl.timesblogmp.security;

import com.sdl.timesblogmp.exception.CustomException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sdl
 * @date 2020/5/12 10:51 上午
 * @description
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private JwtService jwtService;

    /**
     * 判断用户是否在header中携带token
     * ture 放行
     * false 拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = jwtService.getToken(request);
        if (StringUtils.isEmpty(token)){
            throw new CustomException(1001,"token不存在");
        }
        String userName = null;
        try {
            userName = jwtService.getUserName(token);
        }catch (Exception e){
            throw new CustomException(1001,"token失效");
        }

        if (StringUtils.isEmpty(userName)){
            throw new CustomException(1001,"token失效");
        }
        return true;
    }
}
